﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ClassLibraryMessageDataType;
using ClassLibraryNetCom;
using ClassLibraryMessageDispacher;
using System.Threading;
using System.Collections.Concurrent;
using ClassLibraryOverLog;
using xmlTools;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Data.SQLite;
using System.Management;
using ClassLibrarySQLite;
namespace GUI
{
    public partial class DevWork : Form
    {

#region 成员变量
        private Thread devguibackthread = null;

        private ConcurrentQueue<string> notifystrQuence = new ConcurrentQueue<string>();
        private ConcurrentQueue<MessagePackage> updataQuence = new ConcurrentQueue<MessagePackage>();

        private TreeNode allclientTreenode = null; //父节点
        private List<Form> listclients = new List<Form>();

        private ClassMiddleClientBusiness[] allMiddleClientBussiness = new ClassMiddleClientBusiness[10];
        private System.Windows.Forms.Timer mesCenterTimer = new System.Windows.Forms.Timer();
        #endregion

#region 构造
        public DevWork()
        {
            InitializeComponent();
        }

        ~DevWork()
        {
            if (devguibackthread != null)
            {
                devguibackthread.Abort();
                devguibackthread.DisableComObjectEagerCleanup();
            }
        }
        #endregion

#region 初始化工作
        private void initwork(object paobj)
        {
            ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLog(_LogStrClassify.Common, "init start");
            ClassLibrarySQLiteMesManager.DBinit();
            GUICommunicationClass.instance.Equals(this);
            GUICommunicationClass.instance.FunctionNotifyComStr_event = FunctionNotifyComStr_Event_Get_From_Net;
            GUICommunicationClass.instance.FunctionUpdataComMes_event = FunctionUpdataComMes_Event_Get_From_Net;
            DZ_BatteryGrandSysteamMachineNet_Manager.middleMachineDevNet.Equals(paobj); 
            ClassMessagerDispacher.instance.Equals(paobj);
            ClassMessagerDispacher.instance.middleDevNetOut = DZ_BatteryGrandSysteamMachineNet_Manager.middleMachineDevNet.BeginPushMessageInSendingQuence;
            ClassMessagerDispacher.instance.registerDBmesOut(ClassLibrarySQLiteMesManager.PushMessageIntoDBManager);
            DZ_BatteryGrandSysteamMachineNet_Manager.middleMachineDevNet.StartServerListeningWork();
            ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLog(_LogStrClassify.Common, "==DEZUN SYSTEAM  BATTER CHARGE init start over==");
        }
        private void StartDevWorkGUIBackThread()
        {
            devguibackthread = new Thread(dev_gui_back_thread);
            devguibackthread.Priority = ThreadPriority.Normal;
            devguibackthread.IsBackground = true;
            devguibackthread.Start();
            ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLog(_LogStrClassify.Common, "init start back thread");
        }

        string[] cpuid = { "BFEBFBFF000206A7",
                           "BFEBFBFF000806EA",
                           "BFEBFBFF000506E3",
                           "BFEBFBFF000906ED",
                                     "2"
                                        };
        private string GetCPUID()
        {
            System.Management.ManagementClass mc = new ManagementClass("win32_processor");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                return mo["processorid"].ToString();
            }
            return "";

        }

        private unsafe void DevWork_Load(object sender, EventArgs e)
        {
             Console.WriteLine(GetCPUID());

            if(cpuid.Contains( GetCPUID()) == false)
            {
                MessageBox.Show("01 ERR:CPU NOT REGISTER!");
                this.Close();
                return;
            }

            setMiddleClientBussinessArry();
            initwork(this);
            StartDevWorkGUIBackThread();

            setGUI();
            mesCenterTimer.Interval = 500;
            mesCenterTimer.Tick -= mesCentertimerEventHandler;
            mesCenterTimer.Tick += mesCentertimerEventHandler;
            mesCenterTimer.Enabled = true;
            mesCenterTimer.Start();

        }

        private void setMiddleClientBussinessArry()
        {   
            TextBox[] TBOXS= new TextBox[10];
            TBOXS[0] = textBoxIP1;
            TBOXS[1] = textBoxIP2;
            TBOXS[2] = textBoxIP3;
            TBOXS[3] = textBoxIP4;
            TBOXS[4] = textBoxIP5;
            TBOXS[5] = textBoxIP6;
            TBOXS[6] = textBoxIP7;
            TBOXS[7] = textBoxIP8;
            TBOXS[8] = textBoxIP9;
            TBOXS[9] = textBoxIP10;
         
            for (int a = 0; a < allMiddleClientBussiness.Length; a++)
            {
                allMiddleClientBussiness[a] = new ClassMiddleClientBusiness();
                allMiddleClientBussiness[a].middleClientip = "192.168.2." + (a + 1).ToString();
                allMiddleClientBussiness[a].setMiddleclientBusinessStatus(MiddleclientBusinessStatus.outofline);
                allMiddleClientBussiness[a].SetClientTextBoxStatusHandle(ref TBOXS[a]);
            }
        }
        private string GetLocalIPAddress()
        {
            var netInterfaces = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault
                (n => n.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                n.NetworkInterfaceType == NetworkInterfaceType.Ethernet);
            if (netInterfaces == null)
                return string.Empty;

            var address = netInterfaces.GetIPProperties().UnicastAddresses.FirstOrDefault
                (u => u.Address.AddressFamily == AddressFamily.InterNetwork);
            return address?.Address.ToString();
        }
        private void setGUI()
        {
            toolStripStatusLabelservecIP.Text = "服务器已经启动:" + GetLocalIPAddress();
        }
        #endregion

#region 后台线程 工作

        /// <summary>
        /// 后台工作线程
        /// </summary>
        /// <param name="obj"></param>
        private void dev_gui_back_thread(object obj)
        {
            while (true)
            {
                Thread.Sleep(2);
                DealWithNotifyStrEventWork();
                DealWithMiddleDevUpdataEventWork();
            }

        }

        private void clinetConnectEvent(string ip)
        {

#if false
            bool bingexsit = false;
           foreach( TreeNode  varws in   allclientTreenode.Nodes)
            {

                if(varws.Text == ip || varws.Name ==ip)
                {
                    bingexsit = true;
                    break;
                }
            }
           if(bingexsit)
            {
                return;
            }else
            {
               treeViewClients.Invoke((EventHandler)(delegate
                {
                 allclientTreenode.Nodes.Add(ip);       
                //cupboard1 cpi1 = new cupboard1();
                //cpi1.Text = ip;
                //cpi1.MdiParent = this;
                //listclients.Add(cpi1);
                }));
       
            }

#endif
            LogRecord.Log.mInstance.WriteCommonLog("middle dev connect event:" + ip);
            foreach (var c in allMiddleClientBussiness)
            {
                if (c.middleClientip == ip)
                {
                    c.outMiddleclientBusinessStatus(out MiddleclientBusinessStatus itStatus);
                    if (itStatus == MiddleclientBusinessStatus.outofline)
                    {
                        c.setMiddleclientBusinessStatus(MiddleclientBusinessStatus.free);
                        break;
                    }
                }
            }

        }

        private void clinetDisConnectEvent(string ip)
        {
            LogRecord.Log.mInstance.WriteCommonLog("middle dev DIS connect event:" + ip);
            foreach (var c in allMiddleClientBussiness)
            {
                if (c.middleClientip == ip)
                {
                    c.outMiddleclientBusinessStatus(out MiddleclientBusinessStatus itStatus);

                    c.setMiddleclientBusinessStatus(MiddleclientBusinessStatus.outofline);

                    break;


                }
            }
        }
        private void DealWithNotifyStrEventWork()
        {

            if (notifystrQuence.TryDequeue(out string getSentstring))
            {
                string[] eventstr = getSentstring.Split(':');
                switch (eventstr[0])
                {

                    case "CONE":
                        {
                            clinetConnectEvent(eventstr[1]);
                        }
                        break;
                    case "DISC":
                        {
                            clinetDisConnectEvent(eventstr[1]);

                        }
                        break;
                    case "EXCP":
                        {
                            clinetDisConnectEvent(eventstr[1]);
                        }
                        break;


                    default: break;

                }

            }
        }
        private void DealWithMiddleDevUpdataEventWork()
        {

            if (updataQuence.TryDequeue(out MessagePackage outmes))
            {
                string outda = string.Empty;
                int a2 = 0;
                if (ClassDebugDefine.Printf_realtimeDATA == 1)
                { 

                    for (a2 = 0; a2 < outmes.bytesArry.Count; a2++)
                    {
                        outda = outda + " " + outmes.bytesArry.Array[a2].ToString("x2");
                    }
                }
                if (outmes.soure == MessagePackagePath.NetMiddleDeviceCom)
                {
                    if (ClassDebugDefine.Printf_realtimeDATA == 1)
                    {
                          ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLog(_LogStrClassify.Common, "get up tansmit data from middle dev -" + outmes.sdinfo.soureIP + ":" + outda);//日志
                    }
                  // ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLog(_LogStrClassify.Common, "get up tansmit data from middle dev -" + outmes.sdinfo.soureIP + " :real time data");
                    foreach (var c in allMiddleClientBussiness)
                    {
                        if (c.middleClientip == outmes.sdinfo.soureIP)
                        {
                            c.DealPyshInMessages(ref outmes);
                            RefreashForm();
                            break;
                        }
                    }


                } else
                {

                }
            }

        }

#endregion

#region  中位机主动发送数据 回调接口
        /// <summary>
        /// 中位机主动发送数据 回调接口
        /// </summary>
        /// <param name="getMes"></param>
        private void FunctionUpdataComMes_Event_Get_From_Net(ref MessagePackage getMes)
        {
            Console.WriteLine("FunctionUpdata:" + "\r\n");
            updataQuence.Enqueue(getMes);
        }

#endregion

#region 中位机客户端连接响应回调接口
        /// <summary>
        /// 中位机客户端连接响应回调接口
        /// </summary>
        /// <param name="getSentstring"></param>
        private void FunctionNotifyComStr_Event_Get_From_Net(string getSentstring)
        {
            Console.WriteLine("FunctionNotifyComStr:" + getSentstring + "\r\n");
            notifystrQuence.Enqueue(getSentstring);

#if false
            string[] eventstr = getSentstring.Split(':');
            switch (eventstr[0])
            {

                case "CONE":
                    {



                    }
                    break;
                case "DISC":
                    {


                    }
                    break;
                case "EXCP":
                    {


                    }
                    break;


                default: break;

            }
#endif

        }
#endregion

#region 界面关闭 
        private void DevWork_FormClosed(object sender, FormClosedEventArgs e)
        {
            ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLog(_LogStrClassify.Common, "dev form closing");
            if (devguibackthread != null)
            {
                devguibackthread.Abort();
                devguibackthread.DisableComObjectEagerCleanup();
            }
        }

        private void DevWork_FormClosing(object sender, FormClosingEventArgs e)
        {
            ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLog(_LogStrClassify.Common, "dev form closed");
        }

#endregion

#region 工具栏操作
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            ClassLibraryOverLog.ClassOverLogHelper.ShowLogInForm();
        }

#endregion

#region 树状结构控件
        private void treeViewClients_Click(object sender, EventArgs e)
        {
            //TreeNode sec=  e.Node.Nodes;
            // TreeNode sec = treeViewClients.SelectedNode.Nodes;
        }

        private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode secNode = e.Node;

            foreach (var form in listclients)
            {
                if (form.Text == secNode.Text)
                {
                    form.Show();
                    break;
                }
            }
        }
#endregion

        private void button1_Click(object sender, EventArgs e)
        {

            FormWorkStepProjectsHairDown_demo form = new FormWorkStepProjectsHairDown_demo();
            form.ShowDialog();
                     
        }





        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            FormWorkStepProjectsHairDown_demo form = new FormWorkStepProjectsHairDown_demo();
            form.allMiddleClientBussiness = allMiddleClientBussiness;
            form.showClient();
            form.ShowDialog();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (!ClassUI2MiddleCMDCollections.stopWorkSteps("192.168.2.250", out MessagePackage outpack))
            {
                MessageBox.Show("SENT TIME OUT");
            }
            else
            {
                MessageBox.Show("发送成功");
            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            //获取正在连接的ip
#if true
            if (!ClassUI2MiddleCMDCollections.stopWorkSteps("192.168.2.250", out MessagePackage outpack))
            {
                MessageBox.Show("SENT TIME OUT");
            }
            else
            {
                MessageBox.Show("发送成功");
            }
#endif

        }

        private void 构造默认工部方案ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClassWorkStepsProjects koj = new ClassWorkStepsProjects();
            koj.name = "DZ生产测试";
            ClassWorkStepsCollections_chinese k1 = new ClassWorkStepsCollections_chinese();
            k1.工步名称 = "第一";
            ClassWorkStepsCollections_chinese k2 = new ClassWorkStepsCollections_chinese();
            k2.工步名称 = "第二";
            koj.workstepsProjets.Add(k1); koj.workstepsProjets.Add(k2);

            XMLClass.XmlSerialize<ClassWorkStepsProjects>(ref koj, "workProjects", "worp1.Tywps");
        }

        private void 测试数据库ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            string connStr = @"Data Source=e:\2\test23.sqlite3";
            SQLiteConnection conn = new SQLiteConnection(connStr);
            conn.Open();

            string sql = "create table highscores (name varchar(20), score int)";
            SQLiteCommand command = new SQLiteCommand(sql, conn);
            command.ExecuteNonQuery();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void userControl11_Load(object sender, EventArgs e)
        {

        }

        private void 系统ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "警告:确定退出？？？", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                this.Close();
            } else
            {

            }
        }

        private void setClientRealtimeData(string str)
        {


        }

#region 异步刷新页面

        void addre(string str)
        {
            textBox1.BeginInvoke((EventHandler)(delegate
            {
                textBox1.AppendText(str + "\r\n");
            }));
        }
        void ansyRefesForm(string ip, ref OneClientAll64BoardData oneboardall64Bd)
        {
            if (canrefesh == false) return;

            canrefesh = false;

            textBox1.BeginInvoke((EventHandler)(delegate
        {
            textBox1.Clear();
        }));
            for (int a = 0; a < 64; a++)
            {

                string bcodestr = oneboardall64Bd.all64boardBatpointdataAarry[a].boardcode.ToString() + "  号板数据 :==================================";
                addre(bcodestr);
                for (int b = 0; b < 10; b++)
                {
                    byte point = oneboardall64Bd.all64boardBatpointdataAarry[a].oneboardBatpointdataArry[b].positioncode;
                    ushort v = oneboardall64Bd.all64boardBatpointdataAarry[a].oneboardBatpointdataArry[b].volate;
                    ushort c = oneboardall64Bd.all64boardBatpointdataAarry[a].oneboardBatpointdataArry[b].current;
                    ushort cp = oneboardall64Bd.all64boardBatpointdataAarry[a].oneboardBatpointdataArry[b].capacity;
                    byte status = oneboardall64Bd.all64boardBatpointdataAarry[a].oneboardBatpointdataArry[b].status;
                    ushort err = oneboardall64Bd.all64boardBatpointdataAarry[a].oneboardBatpointdataArry[b].errorcode;
                    byte reason = oneboardall64Bd.all64boardBatpointdataAarry[a].oneboardBatpointdataArry[b].finishedreason;
                    string err2jz = ((err & 0xff00) >> 8).ToString("x02") + " " + ((err & 0xff) >> 0).ToString("x02");
                    string logrealPS = string.Format("position:{0} - v:{1} - I:{2} - Cap:{3} - status:{4} - finishedreason:{5}-errcode:{6}", point, v, c, cp, status, reason, err2jz);
                    addre(logrealPS);

                }

            }


        }

        public void RefreashForm()
        {

            IAsyncResult resl = comboBox1.BeginInvoke((EventHandler)(delegate
             {
                 if (comboBox1.Text != "")
                 {
                     int showcIndex = int.Parse(comboBox1.Text);

                     foreach (var c in allMiddleClientBussiness)
                     {
                         if (c.middleClientip == "192.168.2." + showcIndex.ToString())
                         {
                             c.OutOneClientAll64BoardDataObj(out OneClientAll64BoardData OutDba);
                             ansyRefesForm(c.middleClientip, ref OutDba);
                             break;
                         }
                     }

                 }
             }));


        }



#endregion
        bool canrefesh = false;
        private void button1_Click_1(object sender, EventArgs e)
        {
            canrefesh = true;
        }

#region 消息中心负载进度条 定时器

        public void mesCentertimerEventHandler(object sender, EventArgs e)
        {                    
            this.BeginInvoke((EventHandler)(delegate
            {
                toolStripProgressBar1.Value =  ClassMessagerDispacher.instance.GetMessageQuenueCount()>10?10 : ClassMessagerDispacher.instance.GetMessageQuenueCount();

            }));
        }
        #endregion

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            FormClassificationCapacity form = new FormClassificationCapacity();
            //form.allMiddleClientBussiness = allMiddleClientBussiness;
            //form.showClient();
            form.ShowDialog();
        }
    }      
 
}
